package com.ruoyi.worker.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RedisNoUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.worker.domain.OperationalRequirementsTable;
import com.ruoyi.worker.domain.SchemeConfiguration;
import com.ruoyi.worker.mapper.AuditRecordMapper;
import com.ruoyi.worker.mapper.OperationalLogMapper;
import com.ruoyi.worker.mapper.OperationalManagementMapper;
import com.ruoyi.worker.mapper.SchemeConfigurationMapper;
import com.ruoyi.worker.service.OperationalService;
import com.ruoyi.worker.service.v2.RzAttendanceSumDailyRecordV2Service;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName OperationalServiceImpl
 * @Description 运营管理service-impl
 * @Author leizhang
 * Date 2021/10/12 3:40 下午
 * @Version 1.0
 **/
@Service
public class OperationalServiceImpl implements OperationalService {
    @Autowired
    private OperationalManagementMapper operationalManagementMapper;
    @Resource
    private RzAttendanceSumDailyRecordV2Service sumDailyRecordV2Service;
    @Autowired
    private SchemeConfigurationMapper schemeConfigurationMapper;

    @Autowired
    private OperationalLogMapper operationalLogMapper;

    @Autowired
    private AuditRecordMapper auditRecordMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @param requestParams
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * {"equipments":[],"deps":[],}
     * @Description : 获取设备和班组，组别信息
     * @Author : leizhang
     * @Date 3:50 下午 2021/10/12
     **/
    @Override
    public Map<String, Object> getEquipmentAndDeps(Map<String, Object> requestParams) {
        Map<String, Object> resultMap = Maps.newHashMap();
        requestParams.put(Constants.STATUS, 0);
        //1.获取设备信息(全部信息)
        List<Map<String, Object>> equipments = operationalManagementMapper.getEquipments(requestParams);
        //2.获取组别信息
        List<Map<String, Object>> resultList = Lists.newArrayList();
        List<Map<String, Object>> organizationStructureList = operationalManagementMapper.getDepNodes(requestParams);
        //数据过滤 去除没有岗位信息的
        List<Map<String, Object>> organizationStructureFilter = organizationStructureList.stream().filter(organizationStructure -> null != organizationStructure.get("postName")).collect(Collectors.toList());
        //去除重复的regionName
        //数据分组 同一个区域的岗位在一组
        Map<Object, List<Map<String, Object>>> regionMap = organizationStructureFilter.stream().collect(Collectors.groupingBy(deps -> deps.get("regionName")));
        for (List<Map<String, Object>> regionValues : regionMap.values()) {
            resultList.addAll(regionValues);
        }
        Map<String, Object> stringObjectMap = null;
        Map<String, Object> stringObjectMap1 = null;
        for (int i = 0; i < resultList.size() - 1; i++) {
            stringObjectMap = resultList.get(i);

            for (int j = resultList.size() - 1; j > i; j--) {
                stringObjectMap1 = resultList.get(j);
                if (stringObjectMap.get("postName").toString().equals(stringObjectMap1.get("postName"))
                        && stringObjectMap.get("groupName").toString().equals(stringObjectMap1.get("groupName"))
                ) {
                    resultList.remove(j);
                }
            }
        }
        resultMap.put("equipments", equipments);
        resultMap.put("deps", resultList);
        return resultMap;
    }

    /**
     * @param requestParam {"programmeName":"方案名称","standardNumber":"标准人数","businessClassification":"业务分档(单位:w)","deps":{"beginTime":"开始时间","endTime":"结束时间",data:[{"equipmentId":"","equipmentName":"","tableData":"00100111"}]},"equipments":[]}
     * @return void
     * @Description :保存方案信息
     * @Author : leizhang
     * @Date 5:43 下午 2021/10/12
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSchemeConfiguration(Map<String, Object> requestParam) throws Exception {
        //*新增业务量判断业务量去重,统一业务量不可重复插入
        int num = schemeConfigurationMapper.countSchemeConfigurationBybusiness(requestParam);
        if (num != 0) {
            return 1;
        }
        //名称不能重复
        num = schemeConfigurationMapper.getSchemeConfigurationCount(requestParam);
        if (num != 0) {
            return 2;
        }
        //1.插入方案信息主表
        schemeConfigurationMapper.addSchemeConfiguration(requestParam);
        //2.人员配置表信息保存
        Integer configurationId = (Integer) requestParam.get("id");
        if (null == configurationId || null == requestParam.get("deps")) {
            throw new IllegalArgumentException();
        }
        List<Map<String, Object>> equipments = (List<Map<String, Object>>) requestParam.get("deps");
        for (Map<String, Object> equipment : equipments) {
            equipment.put("id", configurationId);
        }
        schemeConfigurationMapper.addStaffingTab(equipments);
        //3.设备信息表保存
        if (null == requestParam.get("equipments") || !(requestParam.get("equipments") instanceof Map)) {
            throw new IllegalArgumentException();
        }
        //设备表格的开始结束时间
        Map<String, Object> depsMap = (Map<String, Object>) requestParam.get("equipments");
        int beginTime = (int) depsMap.get("beginTime");
        int endTime = (int) depsMap.get("endTime");
        List<Map<String, Object>> tableData = (List<Map<String, Object>>) depsMap.get("data");
        for (Map<String, Object> tableDatum : tableData) {
            tableDatum.put("tabData", new JSONArray((List) tableDatum.get("tableData")).toString());
        }
        schemeConfigurationMapper.addEquipmentConfigTab(configurationId, beginTime, endTime, tableData);
        return 0;
    }

    /**
     * @param schemeConfiguration
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description :配置方案信息主表信息获取
     * @Author : leizhang
     * @Date 10:24 上午 2021/10/13
     **/
    @Override
    public List<Map<String, Object>> getSchemeConfigurationTable(SchemeConfiguration schemeConfiguration) {
        List<Map<String, Object>> tableList = schemeConfigurationMapper.getSchemeConfigurationTable(schemeConfiguration);
        return tableList;
    }

    /**
     * @param requestParam
     * @return void
     * @Description : 状态更新
     * @Author : leizhang
     * @Date 5:54 下午 2021/10/13
     **/
    @Override
    @Transactional
    public int updateSchemeConfiguration(Map<String, Object> requestParam) {
        //名称不能重复
        int num = schemeConfigurationMapper.getSchemeConfigurationCount(requestParam);
        if (num != 0) {
            return 2;
        }
        num = schemeConfigurationMapper.countSchemeConfigurationBybusiness(requestParam);
        if (num != 0) {
            return 1;
        }

        List<Integer> ids = new ArrayList<>();
        ids.add(Integer.parseInt(requestParam.get("id") + ""));
        //修改方案主表
        schemeConfigurationMapper.updateSchemeConfiguration(requestParam);
        //2.删除人员信息配置表
        schemeConfigurationMapper.delStaffingInfo(ids);
        //3.删除设备信息
        schemeConfigurationMapper.delEquimentInfo(ids);

        //2.人员配置表信息保存
        Integer configurationId = (Integer) requestParam.get("id");
        if (null == configurationId || null == requestParam.get("deps")) {
            throw new IllegalArgumentException();
        }

        List<Map<String, Object>> equipments = (List<Map<String, Object>>) requestParam.get("deps");
        for (Map<String, Object> equipment : equipments) {
            equipment.put("id", configurationId);
        }
        schemeConfigurationMapper.addStaffingTab(equipments);
        //3.设备信息表保存
        if (null == requestParam.get("equipments") || !(requestParam.get("equipments") instanceof Map)) {
            throw new IllegalArgumentException();
        }
        //设备表格的开始结束时间
        Map<String, Object> depsMap = (Map<String, Object>) requestParam.get("equipments");
        int beginTime = (int) depsMap.get("beginTime");
        int endTime = (int) depsMap.get("endTime");
        List<Map<String, Object>> tableData = (List<Map<String, Object>>) depsMap.get("data");
        for (Map<String, Object> tableDatum : tableData) {
            tableDatum.put("tabData", new JSONArray((List) tableDatum.get("tableData")).toString());
        }
        schemeConfigurationMapper.addEquipmentConfigTab(configurationId, beginTime, endTime, tableData);
        return 0;
    }

    /**
     * @param id
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description :获取配置方案详情
     * @Author : leizhang
     * @Date 9:44 下午 2021/10/13
     **/
    @Override
    public Map<String, Object> getSchemeConfigurationDetail(int id) {
        Map<String, Object> resultMap = Maps.newHashMap();
        SchemeConfiguration schemeConfiguration = schemeConfigurationMapper.getSchemeConfigurationDetail(id);
        resultMap.put("schemeConfiguration", schemeConfiguration);
        List<Map<String, Object>> equipments = schemeConfigurationMapper.getEquipmentsById(id);
        for (Map<String, Object> equipment : equipments) {
            List<Integer> res = JSONObject.parseArray(equipment.get("tableData").toString(), Integer.class);
            equipment.put("tableData", res);
        }
        resultMap.put("equipments", equipments);
        resultMap.put("deps", schemeConfigurationMapper.getStaffingsById(id));
        return resultMap;
    }

    /**
     * @param ids
     * @return void
     * @Description : 方案配置信息删除
     * @Author : leizhang
     * @Date 1:38 下午 2021/10/18
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSchemeConfigurationInfo(List<Integer> ids) {
        if (ids.isEmpty()) {
            throw new IllegalArgumentException();
        }
        //1.主表信息删除
        schemeConfigurationMapper.delSchemeConfigurationInfo(ids);
        //2.删除人员信息配置表
        schemeConfigurationMapper.delStaffingInfo(ids);
        //3.删除设备信息
        // schemeConfigurationMapper.delEquimentInfo(ids);
    }

    /**
     * @param requestParam
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description :运营需求单-班组/班次信息获取/策略信息获取
     * @Author : leizhang
     * @Date 1:38 下午 2021/10/14
     **/
    @Override
    public Map<String, Object> getTimeShiftAndDep(Map<String, Object> requestParam) {
        requestParam.putIfAbsent(Constants.STATUS, 1);
        requestParam.putIfAbsent("depStatus", 0);
        requestParam.putIfAbsent("delFlag", 0);
        requestParam.putIfAbsent("category", 2);
        //班次信息获取
        List<Map<String, Object>> timeShiftList = schemeConfigurationMapper.getTimShiftInfo(requestParam);
        //班组信息获取
        List<Map<String, Object>> depInfo = schemeConfigurationMapper.getDepInfo(requestParam);
        //策略信息获取
        List<Map<String, Object>> strategyInfo = schemeConfigurationMapper.getStrategyInfo(requestParam);
        Map<String, Object> result = Maps.newHashMap();
        result.put("timeShift", timeShiftList);
        result.put("deps", depInfo);

        //启用预测业务量方案
        boolean ywFlag = false;
        //方案预测
        boolean faFlag = false;
        for (Map<String, Object> strategy : strategyInfo) {
            if ("ygywlqsfs".equals(strategy.get("strategyCode"))) {
                ywFlag = 2 == (int) strategy.get("strategyValue");
            }
            if ("qdfappfs".equals(strategy.get("strategyCode"))) {
                faFlag = 2 == (int) strategy.get("strategyValue");
            }
        }
        result.put("strategyYw", ywFlag);
        result.put("strategyFa", faFlag);
        //如果是手填的 下拉显示可选方案
        if (!faFlag) {
            List<Map<String, Object>> schemeConfiguration = schemeConfigurationMapper.getSchemeConfiguration(requestParam);
            result.put("faResult", schemeConfiguration);
        }
        //人员基本信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //填写人员姓名
        result.put("businessFillingName", loginUser.getUser().getUserName());
        //部门id
        result.put("deptId", loginUser.getUser().getDeptId());
        //部门名称
        result.put("deptName", loginUser.getUser().getDept().getDeptName());
        //岗位信息
        Long userId = loginUser.getUserId();
        List<Map<String, Object>> userPosts = schemeConfigurationMapper.getUserPosts(userId);
        result.put("posts", userPosts);
        return result;
    }

    /**
     * @param requestParam {"workTime":"用工时间","timeShiftId":"班次id","predictNumber":"预测数量","bequeath":"班组遗留"}
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description : 获取业务预估量
     * @Author : leizhang
     * @Date 2:32 下午 2021/10/14
     **/
    @Override
    public AjaxResult getQualityPredictInfo(Map<String, Object> requestParam) {
        Map<String, Object> resultMap = Maps.newHashMap();
        //预估业务判断是否启用策略
        requestParam.put("strategyCode", "ygywlqsfs");
        List<Map<String, Object>> strategyInfoYw = schemeConfigurationMapper.getStrategyInfo(requestParam);
        int strategyYwValue = (int) strategyInfoYw.get(0).get("strategyValue");
        if (2 == strategyYwValue) {
            requestParam.put("taskNode", 1);
            List<Map<String, Object>> qualityPredicts = schemeConfigurationMapper.getQualityPredict(requestParam);
            if (qualityPredicts.isEmpty()) {
                return AjaxResult.error(StringUtils.format("用日期:{},班次:{} 无对应质量预估信息请核对", requestParam.get("workTime").toString(), requestParam.get("timeShiftId").toString()));
            } else {
                Map<String, Object> ywMap = qualityPredicts.get(0);
                double predictNumber = Double.parseDouble(ywMap.get("future24PredictNumber").toString()) - Double.parseDouble(ywMap.get("future12PredictNumber").toString()) + Double.parseDouble(ywMap.get("provinceNotIssued").toString()) + Double.parseDouble(requestParam.get("bequeath").toString());
                requestParam.put("predictNumber", predictNumber);
                ywMap.put("predictNumber", predictNumber);
                resultMap.put("strategyYw", ywMap);
            }
        }
        //启用方案
        requestParam.put("strategyCode", "qdfappfs");
        List<Map<String, Object>> strategyInfo = schemeConfigurationMapper.getStrategyInfo(requestParam);
        int strategyValue = (int) strategyInfo.get(0).get("strategyValue");
        if (2 == strategyValue) {
            //方案策略启用自动匹配
            List<Map<String, Object>> schemeConfiguration = schemeConfigurationMapper.getSchemeConfiguration(requestParam);
            if (schemeConfiguration.isEmpty()) {
                return AjaxResult.error(-2, "获取预估业务量失败");
            }
            Map<String, Object> predictNumber = getStrategyResult(schemeConfiguration, Double.parseDouble(requestParam.get("predictNumber").toString()));
            resultMap.put("strategyFa", predictNumber);
        }
        resultMap.put("orderCode", RedisNoUtil.getAddNo("YZOYW", redisTemplate));
        return AjaxResult.success(resultMap);
    }

    //算法自动获取启用方案(双指针取数据)
    public Map<String, Object> getStrategyResult(List<Map<String, Object>> data, double predictNumber) {
        int length = data.size();
        double headValue = 0.0;
        double nextValue = 0.0;
        //第一指针
        int indexOne = 0;
        //第二指针
        int indexTwo = 0;
        if (length == 1) {
            headValue = (double) data.get(0).get("businessClassification");
        } else {
            for (int i = 0, j = i + 1; i < length; ) {
                double number = (double) data.get(i).get("businessClassification");
                if (predictNumber <= number) {
                    headValue = number;
                    indexOne = i;
                    break;
                }
                double nextNumber = (double) data.get(j).get("businessClassification");
                if (predictNumber >= number && predictNumber <= nextNumber) {
                    headValue = number;
                    nextValue = nextNumber;
                    indexOne = i;
                    indexTwo = j;
                    break;
                }
                if (j == length - 1) {
                    headValue = nextNumber;
                    indexOne = j;
                    break;
                }
                i++;
                j++;
            }
        }
        //四舍五入取业务分档(单位:w) 当前业务量-第一档/第二档减去第一档
        if (0 == headValue || 0 == nextValue) {
            return data.get(indexOne);
        } else {
            //当前业务量-第一档/第二档 - 第一档
            double res = (predictNumber - headValue) / (nextValue - headValue);
            double threshold = 1;
            if (res < threshold) {
                //小于0.5 取第一个
                return data.get(indexOne);
            } else {
                return data.get(indexTwo);
            }
        }
    }

    /**
     * @param id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description : 配置方案信息 获取以及策略信息获取
     * @Author : leizhang
     * @Date 11:01 上午 2021/10/15
     **/
    @Override
    public Map<String, Object> getSchemeConfigurationAndStrategy(int id) {
        Map<String, Object> schemeConfigurationDetail = this.getSchemeConfigurationDetail(id);
        //策略信息获取
        List<Map<String, Object>> businessVolume = schemeConfigurationMapper.getBusinessVolume();
        if (null == businessVolume || businessVolume.isEmpty()) {
            schemeConfigurationDetail.put("strategyType", 0);
            schemeConfigurationDetail.put("strategyCx", "");
        } else if (1 == (int) businessVolume.get(0).get("businessVolumeType")) {
            schemeConfigurationDetail.put("strategyType", 1);
            schemeConfigurationDetail.put("strategyCx", businessVolume.get(0).get("businessVolumeValue"));
        } else {
            schemeConfigurationDetail.put("strategyType", 2);
            for (Map<String, Object> business : businessVolume) {
                for (Map.Entry<String, Object> entry : business.entrySet()) {
                    if (entry.getKey().equals("businessId") && entry.getValue().equals(id)) {
                        schemeConfigurationDetail.put("strategyCx", business.get("businessVolumeValue"));
                    }
                }
            }
        }
        return schemeConfigurationDetail;
    }

    /**
     * @param requestParam {"staffing":[{}]}
     * @return void
     * @Description : 运营需求单
     * @Author : leizhang
     * @Date 2:25 下午 2021/10/15
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOperationalInfo(Map<String, Object> requestParam) {
        //1.新增运营需求单  手动输入校验单据号是否重复  运营需求单：YZOYW+数字/字母（总字符长度限制10，单据提交单据编号验重）
        String orderCode = null;
        if (StrUtil.isEmpty(orderCode = requestParam.get("orderCode").toString())) {
            throw new IllegalArgumentException("orderCode参数异常");
        }
//        if (orderCode.indexOf("YZOYW") == -1 || orderCode.length() > 10) {
//            //参数规则不合法
//            return -1;
//        }
        List<Map<String, Object>> operationalInfo = operationalManagementMapper.getOperationalInfo(requestParam);
        if (!operationalInfo.isEmpty()) {
            return -2;
        }
        if (null != requestParam.get("urls") && requestParam.get("urls") instanceof List) {
            List<String> uploadFiles = (List) requestParam.get("urls");
            if (!uploadFiles.isEmpty()) {
                String urls = Joiner.on(";").join(uploadFiles);
                requestParam.put("uploadFiles", urls);
            }
        }
        schemeConfigurationMapper.addOperationalInfo(requestParam);
        if (null == requestParam.get("id") || null == requestParam.get("deps")) {
            throw new IllegalArgumentException();
        }
        Object staffings = null;
        if (!((staffings = requestParam.get("deps")) instanceof List)) {
            throw new IllegalArgumentException();
        }
        int affairId = (int) requestParam.get("id");
        schemeConfigurationMapper.addOperationalRequirementsDetails((List) staffings, affairId);
        //2.新增操作日志记录
        Map<String, Object> reqMap = Maps.newHashMap();
        long userId = SecurityUtils.getLoginUser().getUserId();
        String userName = requestParam.get("businessFillingName").toString();
        int deptId = (int) requestParam.get("deptId");
        String deptName = requestParam.get("deptName").toString();
        reqMap.put("updateId", userId);
        reqMap.put("updateName", userName);
        reqMap.put("updateDeptId", deptId);
        reqMap.put("updateDeptName", deptName);
        reqMap.put("affairId", affairId);
        operationalLogMapper.addOperationalLogInfo(reqMap);
//        //3.添加待审核记录
//        Map<String, Object> auditMap = Maps.newHashMap();
//        auditMap.put("auditTime", new Date());
//        auditMap.put("auditId", userId);
//        auditMap.put("auditName", userName);
//        auditMap.put("auditDeptId", deptId);
//        auditMap.put("auditDeptName", deptName);
//        auditMap.put("auditStatus", 1);
//        auditMap.put("auditResult", 1);
//        auditMap.put("auditAffairId", affairId);
//        auditRecordMapper.addSysAuditRecord(auditMap);
        return 1;
    }

    /**
     * @param requestParam
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description : 获取运营需求单列表
     * @Author : leizhang
     * @Date 9:16 下午 2021/10/15
     **/
    @Override
    public List<Map<String, Object>> getOperationalList(Map<String, Object> requestParam) {
        return operationalManagementMapper.getOperationalList(requestParam);
    }

    /**
     * @param requestParam {"id":,"enableSchemeId":"启用方案id"}
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description : 运营需求单详情获取
     * @Author : leizhang
     * @Date 11:20 下午 2021/10/15
     **/
    @Override
    public Map<String, Object> getOperationalDetail(Map<String, Object> requestParam) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMap();
        List<Map<String, Object>> operationalList = this.getOperationalList(requestParam);
        if (operationalList.size() > 1 || operationalList.isEmpty()) {
            throw new Exception("数据异常");
        }
        Map<String, Object> operationalInfo = operationalList.get(0);
        resultMap.put("baseData", operationalInfo);
        if (null != operationalInfo.get("uploadFiles")) {
            String uploadFiles = operationalInfo.get("uploadFiles").toString();
            resultMap.put("urls", Splitter.on(";").split(uploadFiles));
        }
        //获取人员详细详情信息
        List<Map<String, Object>> operationalStraffing = operationalManagementMapper.getOperationalStraffing(Integer.parseInt(requestParam.get("id").toString()));
        resultMap.put("deps", operationalStraffing);
        //获取设备信息
        List<Map<String, Object>> equipments = schemeConfigurationMapper.getEquipmentsById(Integer.parseInt(requestParam.get("enableSchemeId").toString()));
        for (Map<String, Object> equipment : equipments) {
            List<Integer> res = JSONObject.parseArray(equipment.get("tableData").toString(), Integer.class);
            equipment.put("tableData", res);
        }
        resultMap.put("equipments", equipments);
        //操作日志信息获取
        List<Map<String, Object>> operationalLogInfo = operationalLogMapper.getOperationalLogInfo(requestParam);
        resultMap.put("operationLogs", operationalLogInfo);
        //审核日志信息查询
        List<Map<String, Object>> auditInfo = auditRecordMapper.getAuditInfo(requestParam);
        resultMap.put("auditLogs", auditInfo);
        return resultMap;
    }

    /**
     * @param requestParam {"auditResult":2,"id":"运营需求单主表id"}
     * @return void
     * @Description : 审核状态更新
     * @Author : leizhang
     * @Date 9:57 下午 2021/10/16
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAuditInfo(Map<String, Object> requestParam) {
        //1.记录审核信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        //操作人姓名
        String userName = user.getUserName();
        //操作人id
        Long userId = user.getUserId();
        //操作人部门id
        Long deptId = user.getDeptId();
        //操作人部门名称
        String deptName = user.getDept().getDeptName();
        //主表id
        int id = (int) requestParam.get("id");
        requestParam.put("auditTime", new Date());
        requestParam.put("auditId", userId);
        requestParam.put("auditName", userName);
        requestParam.put("auditDeptId", deptId);
        requestParam.put("auditDeptName", deptName);
        requestParam.put("auditStatus", 2);
        requestParam.put("auditAffairId", id);
        auditRecordMapper.addSysAuditRecord(requestParam);
        if (null == requestParam.get("audId")) {
            throw new IllegalArgumentException();
        }
        //2.日志记录
        requestParam.put("updateId", userId);
        requestParam.put("updateName", userName);
        requestParam.put("updateDeptId", deptId);
        requestParam.put("updateDeptName", deptName);
        requestParam.put("affairId", id);
        requestParam.put("updateType", 4);
        operationalLogMapper.addOperationalLogInfo(requestParam);
        //3.更新主表状态
        operationalManagementMapper.updateAuditStatus(requestParam);
        //4.查询主表信息id
        List<Map<String, Object>> operationalInfo = operationalManagementMapper.getOperationalInfo(requestParam);
        Map<String, Object> workNeed = operationalInfo.get(0);
        //5.审核通过之后新增用工需求
        String documentNumber = "YGXQ".concat(DateUtils.dateTimeNow()).concat(IdUtils.fastSimpleUUID().substring(0, 3));
        workNeed.put("documentNumber", documentNumber);
        operationalManagementMapper.addWorkerNeed(workNeed);

    }

    /**
     * @param requestParam
     * @return void
     * @Description : 运营需求单修改
     * @Author : leizhang
     * @Date 10:16 下午 2021/10/17
     **/
    @Override
    public void updateOperationalInfo(Map<String, Object> requestParam) {
        //1.前提：主表id不能为空
        if (null == requestParam.get("id")) {
            throw new IllegalArgumentException();
        }
        int operationalId = (int) requestParam.get("id");
        //2.修改主表数据
        if (null != requestParam.get("urls") && requestParam.get("urls") instanceof List) {
            List<String> uploadFiles = (List<String>) requestParam.get("urls");
            if (!uploadFiles.isEmpty()) {
                requestParam.put("uploadFiles", Joiner.on(";").join(uploadFiles));
            }
        }
        operationalManagementMapper.updateOperationalInfo(requestParam);
        //3.人员配置信息修改 选删除 再新增
        operationalManagementMapper.delOperationalDetailInfo(operationalId);
        Object staffings = null;
        if (null != requestParam.get("deps") && !((staffings = requestParam.get("deps")) instanceof List)) {
            throw new IllegalArgumentException();
        }
        schemeConfigurationMapper.addOperationalRequirementsDetails((List) staffings, operationalId);
        //4.添加修改日志
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        requestParam.put("updateId", user.getUserId());
        requestParam.put("updateName", user.getUserName());
        requestParam.put("updateDeptId", user.getDeptId());
        requestParam.put("updateDeptName", user.getDept().getDeptName());
        requestParam.put("affairId", operationalId);
        requestParam.put("updateType", 2);
        operationalLogMapper.addOperationalLogInfo(requestParam);
    }

    /**
     * @param ids
     * @return void
     * @Description : 运营需求单删除
     * @Author : leizhang
     * @Date 2:35 下午 2021/10/18
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delOperationalInfo(List<Integer> ids) {
        if (ids.isEmpty()) {
            throw new IllegalArgumentException();
        }
        //1.删除运营需求表信息
        operationalManagementMapper.delOperationalInfo(ids);
        //2.删除详情表
        operationalManagementMapper.delOperationalDetailInfos(ids);
        //3.日志记录信息删除
        operationalManagementMapper.delOperationalLog(ids);
        //4.审核记录删除
        operationalManagementMapper.delOperationalAudit(ids);
    }

    @Override
    public List<Map<String, Object>> getTimShiftInfo(Map<String, Object> requestParam) {
        return schemeConfigurationMapper.getTimShiftInfo(requestParam);
    }

    /**
     * 更新用工需求预测需求人数
     *
     * @param requestParam: {id:主键,demandNumber:实际用工人数}
     * @author Hush.
     * @since 2021/11/29 19:19
     */
    @Override
    public void updateDemandNumber(Map<String, Object> requestParam) {
        operationalManagementMapper.updateDemandNumber(requestParam);
    }

    /**----------------运营需求单修改-------------**/
    /**
     * 新增运营需求(二期)
     *
     * @param operationalRequirementsTable 运营需求(二期)
     * @return 结果
     */
    @Override
    public int insertOperationalRequirementsTable(OperationalRequirementsTable operationalRequirementsTable) {
        //同一用工日期+班组组合，只能提交1次。原订单删除后，才可以新建。
        List<OperationalRequirementsTable> operationalRequirementsTables = operationalManagementMapper.selectOperationalRequirements(operationalRequirementsTable);
        if (operationalRequirementsTables.size() > 0) {
            return -1;
        }
        return operationalManagementMapper.insertOperationalRequirementsTable(operationalRequirementsTable);
    }

    /**
     * 修改运营需求(二期)
     *
     * @param operationalRequirementsTable 运营需求(二期) {"staffings":[{}],optionalId:""}
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOperationalRequirementsTable(OperationalRequirementsTable operationalRequirementsTable) {
//        Integer taskNode = operationalRequirementsTable.getTaskNode();
//        Integer status = 0;
//        if (taskNode == 2) {
//            // 质量审核通过，填写用工评估
//            schemeConfigurationMapper.addOperationalRequirementsDetails(operationalRequirementsTable.getStaffings(), Integer.parseInt(operationalRequirementsTable.getId().toString()));
//        }
//        //获取当前节点
//        if (taskNode == 5) {
//            status = 11;
//        } else if (taskNode == 2) {
//            status = 4;
//        } else if (taskNode == 3) {
//            status = 7;
//        } else if (taskNode == 4) {
//            status = 9;
//        }
//        operationalRequirementsTable.setStatus(status);
//        operationalManagementMapper.updateOperationalRequirementsTable(operationalRequirementsTable);
//        //启动流程
//        Map<String,Object> requestParam = Maps.newHashMap();
//        requestParam.put("processDefinitionKey","yyxq_event");
//        requestParam.put("processType",1);
//        requestParam.put("processInstanceName","运营需求单审核");
//        requestParam.put("businessKey",operationalRequirementsTable.getId());
//        Map<String,Object> variables = Maps.newHashMap();
//        variables.put("auditFlag",taskNode);
//        requestParam.put("variables",variables);
//        operationalWorkFlowService.startOperationalWorkFlowProcess(requestParam);
        return 1;
    }

    /**
     * @param operationalRequirementsTable
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description : 根据当班预测量获取方案信息
     * @Author : leizhang
     * @Date 9:47 PM 2021/12/23
     **/
    @Override
    public Map<String, Object> getFaInfo(OperationalRequirementsTable operationalRequirementsTable) {
        Map<String, Object> result = Maps.newHashMap();
        //1.获取策略配置值
        List<Map<String, Object>> strategyInfo = schemeConfigurationMapper.getStrategyInfo(Maps.newHashMap());
        //方案预测 2 启动
        boolean faFlag = false;
        for (Map<String, Object> strategy : strategyInfo) {
            if ("qdfappfs".equals(strategy.get("strategyCode"))) {
                faFlag = 2 == (int) strategy.get("strategyValue");
            }
        }
        //2.如果方案启动，则获取对应的方案值，否则返回方案下拉
        List<Map<String, Object>> schemeConfiguration = schemeConfigurationMapper.getSchemeConfigurationOfOperational(operationalRequirementsTable);
        if (!faFlag) {
            result.put("strategyValue", "false");
            result.put("faResult", schemeConfiguration);
        } else {
            //自动匹配
            if (schemeConfiguration.isEmpty()) {
                return AjaxResult.error(-2, "获取方案信息失败");
            }
            result.put("strategyValue", "true");
            Map<String, Object> predictNumber = getStrategyResult(schemeConfiguration, Double.parseDouble(operationalRequirementsTable.getGroupEstimateNumber().toString()));
            result.put("faResult", predictNumber);
        }
        return result;
    }

    /**
     * @param requestParam
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description :  获取对应日期班次排班信息
     * @Author : leizhang
     * @Date 10:59 PM 2021/12/26
     **/
    @Override
    public Map<String, Object> getWorkerNumber(Map<String, Object> requestParam) throws Exception {
        Map<String, Object> result = Maps.newHashMap();
        int attendanceNumber = operationalManagementMapper.getWorkerNumber(requestParam);
        result.put("workNumber", attendanceNumber);
        List<Map<String, Object>> businessVolume = schemeConfigurationMapper.getBusinessVolume();
        if (null == businessVolume || businessVolume.isEmpty()) {
            result.put("strategyType", 0);
            result.put("strategyCx", 0);
        } else if (1 == (int) businessVolume.get(0).get("businessVolumeType")) {
            result.put("strategyType", 1);
            result.put("strategyCx", businessVolume.get(0).get("businessVolumeValue"));
        } else {
            result.put("strategyType", 2);
            for (Map<String, Object> business : businessVolume) {
                for (Map.Entry<String, Object> entry : business.entrySet()) {
                    if (entry.getKey().equals("businessId") && entry.getValue().equals(requestParam.get("id"))) {
                        result.put("strategyCx", business.get("businessVolumeValue"));
                    }
                }
            }
        }
        return result;
    }

    /**
     * 查询运营需求(二期)
     *
     * @param id 运营需求(二期)主键
     * @return 运营需求(二期)
     */
    @Override
    public OperationalRequirementsTable selectOperationalRequirementsTableById(Integer id) {
        //获取设备信息

        OperationalRequirementsTable operationalRequirementsTable = operationalManagementMapper.selectOperationalRequirementsTableById(id);
        Integer taskNode = operationalRequirementsTable.getTaskNode();
        Integer status = operationalRequirementsTable.getStatus();
        if (taskNode > 1 && status > 3) {
            List<Map<String, Object>> equipments = schemeConfigurationMapper.getEquipmentsById(Integer.parseInt(operationalRequirementsTable.getSchemeConfigurationId().toString()));
            for (Map<String, Object> equipment : equipments) {
                List<Integer> res = JSONObject.parseArray(equipment.get("tableData").toString(), Integer.class);
                equipment.put("tableData", res);
            }
            operationalRequirementsTable.setEquipments(equipments);
            String uploadFiles1 = operationalRequirementsTable.getUploadFiles();
            if (null != uploadFiles1 && "" != uploadFiles1) {
                if (uploadFiles1.indexOf(";") > 0) {
                    List<String> strings = Splitter.on(";").splitToList(uploadFiles1);
                    operationalRequirementsTable.setUrls(strings);
                } else {
                    List<String> urlsList = Lists.newArrayList();
                    urlsList.add(uploadFiles1);
                    operationalRequirementsTable.setUrls(urlsList);
                }
            }
            //获取人员详细详情信息
            List<Map<String, Object>> operationalStraffing = operationalManagementMapper.getOperationalStraffing(Integer.parseInt(id.toString()));
            operationalRequirementsTable.setDeps(operationalStraffing);
        }
        //审核日志信息查询
        Map<String, Object> requestParam = Maps.newHashMap();
        requestParam.put("id", id);
        requestParam.put("auditType", 1);
        List<Map<String, Object>> auditInfo = auditRecordMapper.getAuditInfo(requestParam);
        operationalRequirementsTable.setAuditLogs(auditInfo);
        return operationalRequirementsTable;
    }

    /**
     * 查询运营需求(二期)列表
     *
     * @param operationalRequirementsTable 运营需求(二期)
     * @return 运营需求(二期)
     */
    @Override
    public List<OperationalRequirementsTable> selectOperationalRequirementsTableList(OperationalRequirementsTable operationalRequirementsTable) {
        return operationalManagementMapper.selectOperationalRequirementsTableList(operationalRequirementsTable);
    }

    /**
     * 删除运营需求(二期)信息
     *
     * @param id 运营需求(二期)主键
     * @return 结果
     */
    @Override
    public int deleteOperationalRequirementsTableById(Long id) {
        return operationalManagementMapper.deleteOperationalRequirementsTableById(id);
    }


    @Override
    public void updateOperationalById(OperationalRequirementsTable operationalRequirementsTable) {
        operationalManagementMapper.updateOperationalStatusById(operationalRequirementsTable);
    }

    /**
     * @param requestParam
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description : 获取长期工 临时工考勤信息
     * @Author : leizhang
     * @Date 1:58 PM 2021/12/29
     **/
    @Override
    public Map<String, Object> getAttendanceInformation(Map<String, Object> requestParam) throws Exception {
        Map<String, Object> resultMap = Maps.newHashMap();
        // 时间
        String date = requestParam.get("workTime").toString();
        //班组id
        Integer deptId = Integer.parseInt(requestParam.get("groupId").toString());
        // 考勤组 白班 1 夜班 2 通班3  班次表  夜班17 白班14 通班21 主要不想改 就用这种垃圾方式
        Integer groupId = Integer.parseInt(requestParam.get("timeShiftId").toString());
        //1.长期工出勤信息获取
        Integer numver = 0;
        if (groupId == 14) {
            // 白班人数
            ImmutableMap<String, Object> statistics_day = sumDailyRecordV2Service.statistics(date, 1, deptId);
            if (!ObjectUtils.isEmpty(statistics_day)) {
                ArrayList<Map<String, Object>> total = (ArrayList) statistics_day.get("total");
                numver = Integer.parseInt(total.get(0).get("result").toString());
            }
        }
        ImmutableMap<String, Object> statistics = sumDailyRecordV2Service.statistics(date, 3, deptId);
        if (!ObjectUtils.isEmpty(statistics)) {
            // 夜班人数
            ArrayList<Map<String, Object>> total = (ArrayList) statistics.get("total");
            for (Map<String, Object> stringObjectMap : total) {
                Integer workType = (Integer) stringObjectMap.get("workType");
                int wo = groupId == 17? 2 : groupId==14?1:0;
                if (wo == workType) {
                    numver += Integer.parseInt(stringObjectMap.get("result").toString());
                }
            }
        }

        resultMap.put("attendanceInformationOfCq", numver);
        //2.临时工出勤信息获取
        Long attendanceInformationOfTerm = operationalManagementMapper.getAttendanceInformationOfTerm(requestParam);

        resultMap.put("attendanceInformationOfTerm", attendanceInformationOfTerm);

        return resultMap;
    }
}
